<template>
    <lay-table :page="page" :columns="columns" :data-source="dataSource" resize :loading="loading"
        :default-toolbar="defaultToolbars" :height="tableHeight" style="height: 100%;">
        <template v-slot:toolbar>
            <!-- 数据筛选 -->
            <lay-form :model="queryForm" ref="addTreeSpeciesForm" isLabelTooltip>
                <lay-form-item prop="city" mode="inline" size="xs" style="margin-bottom: 0;">
                    <lay-select v-model="queryForm.city" multiple showSearch allow-clear minCollapsedNum=1
                        placeholder="市" size="xs">
                        <lay-select-option v-for="city in selectList.cityList" :key="city" :value="city"
                            :label="city"></lay-select-option>
                    </lay-select>
                </lay-form-item>
                <lay-form-item prop="county" mode="inline" size="xs" style="margin-bottom: 0;">
                    <lay-select v-model="queryForm.county" multiple showSearch allow-clear minCollapsedNum=1
                        placeholder="区/县" size="xs">
                        <lay-select-option v-for="county in selectList.countyList" :key="county" :value="county"
                            :label="county"></lay-select-option>
                    </lay-select>
                </lay-form-item>
                <lay-form-item prop="town" mode="inline" size="xs" style="margin-bottom: 0;">
                    <lay-select v-model="queryForm.town" multiple showSearch allow-clear minCollapsedNum=1
                        placeholder="乡/镇" size="xs">
                        <lay-select-option v-for="town in selectList.townList" :key="town" :value="town"
                            :label="town"></lay-select-option>
                    </lay-select>
                </lay-form-item>
                <lay-form-item prop="town" mode="inline" size="xs" style="margin-bottom: 0;">
                    <lay-select v-model="queryForm.forestClass" multiple showSearch allow-clear minCollapsedNum=1
                        placeholder="森林类别" size="xs">
                        <lay-select-option v-for="value in selectList.forestClassList" :key="value.id" :value="value"
                            :label="value"></lay-select-option>
                    </lay-select>
                </lay-form-item>
                <lay-form-item prop="town" mode="inline" size="xs" style="margin-bottom: 0;">
                    <lay-select v-model="queryForm.ecologicalZone" multiple showSearch allow-clear minCollapsedNum=1
                        placeholder="生态分区" size="xs">
                        <lay-select-option v-for="value in selectList.ecologicalZoneList" :key="value.id" :value="value"
                            :label="value"></lay-select-option>
                    </lay-select>
                </lay-form-item>
            </lay-form>
        </template>

        <template v-for="child in slotChildren" :key="child.key" v-slot:[child.customSlot]="{ row }">
            <span v-if="row[child.key] <= 0"
                style="color:red;display: block;width: 100%;height: 100%;background-color: rgb(255 149 149 / 5%);">
                {{ row[child.key] }}
            </span>
            <span v-else>{{ row[child.key] }}</span>
        </template>

        <template v-slot:operator="{ row }">
            <lay-button size="xs" border="green" @click="handleDialogValue(row)">修改参数值</lay-button>
        </template>

    </lay-table>
    <Dialog v-model="dialogVisible" :dialogVisible="dialogVisible" :id="id" :resource_id="resource_id"
        :dialogTitle="dialogTitle" @initDataList="initDataList"></Dialog>
</template>

<script setup>
import { onMounted, watch, ref, reactive, computed } from 'vue'
import api from '@/api';
import Dialog from '@/views/param/components/dialog.vue'

const edingKeys = ref([])
const dataSource = ref([])
const loading = ref(true)
const queryForm = ref({
    pageNum: 1,
    pageSize: 20,
    province: ["广西"],
    city: [],
    county: [],
    town: [],
    village: [],
    forestClass: [],
    ecologicalZone: []
})

// 新增、编辑 dialog
const id = ref(-1)
const resource_id = ref(-1)
const dialogVisible = ref(false)
const dialogTitle = ref('')

// 计算表格高度
const tableHeight = computed(() => {
    return window.innerHeight - 90 + 'px'
})

const handleDialogValue = (row) => {
    if (row) {
        id.value = row.id;
        resource_id.value = row.resource;
        dialogTitle.value = "数据修改"
    } else {
        id.value = -1;
        dialogTitle.value = "添加数据"
    }
    dialogVisible.value = true
}

const page = reactive({ current: 1, limit: 20, limits: [20, 50, 100], total: dataSource.value.length, layout: ["page", "limits", "prev", "refresh", "count", "next", "skip",] });
// 分页、排序、筛选等参数
const change = (page) => {
    queryForm.value.pageNum = page.current;
    queryForm.value.pageSize = page.limit;
    loading.value = true;
    initDataList();
}
// attach change handler to page prop per layui-vue new API
page.change = change;

const editHandle = (data) => {
    edingKeys.value.push(data);
    console.log(data);
}

const deleteEdit = (data) => {
    console.log('@1', edingKeys.value)
    edingKeys.value.splice(edingKeys.value.indexOf(data), 1);
    console.log('@2', edingKeys.value)
}

const columns = [
    { title: "ID", key: "id", fixed: "left", align: 'center', width: '50px' },
    { title: "资源ID", key: "resource", fixed: "left", align: 'center', width: '60px' },
    { title: "省/自治区", key: "province", align: 'center', ellipsisTooltip: true, hide: true, },
    { title: "市", key: "city", align: 'center', ellipsisTooltip: true, },
    { title: "区/县", key: "county", align: 'center', ellipsisTooltip: true, },
    { title: "乡/镇", key: "town", align: 'center', ellipsisTooltip: true, hide: true, },
    { title: "村", key: "village", align: 'center', ellipsisTooltip: true, hide: true, },
    { title: "植被生态区", key: "vegetation_ecological_zone_name", align: 'center', ellipsisTooltip: true, hide: true, },
    { title: "生态工程区", key: "ecological_engineering_zone_name", align: 'center', ellipsisTooltip: true, hide: true, },
    { title: "生态分区", key: "ecological_zone_name", align: 'center', ellipsisTooltip: true, },
    { title: "森林类别", key: "forest_class_name", align: 'center', ellipsisTooltip: true, },
    { title: "事权级", key: "forest_class_level", align: 'center', ellipsisTooltip: true, hide: true, },
    { title: "生态分区2", key: "ecological_zone_2", align: 'center', ellipsisTooltip: true, hide: true, },
    { title: "优势树种", key: "dominant_tree_species_name", align: 'center', ellipsisTooltip: true, },
    { title: "起源", key: "origin_name", align: 'center', ellipsisTooltip: true, },
    { title: "年龄组", key: "age_group_name", align: 'center', ellipsisTooltip: true, },
    {
        title: "保育土壤", align: 'center', children: [
            { title: "固土", key: "U_gt", align: 'center', ellipsisTooltip: true, },
            { title: "保肥", key: "U_bf", align: 'center', ellipsisTooltip: true, },
        ]
    },
    {
        title: "林木养分固持", align: 'center', children: [
            { title: "氮固持", key: "U_NL", align: 'center', ellipsisTooltip: true, },
            { title: "磷固持", key: "U_PL", align: 'center', ellipsisTooltip: true, },
            { title: "钾固持", key: "U_KL", align: 'center', ellipsisTooltip: true, },
        ]
    },

    { title: "备注", key: "remark", ellipsisTooltip: true, hide: true, },
    { title: "操作", key: "operator", customSlot: "operator", fixed: "right", ignoreExport: true, align: 'center', width: "90px" },
]
const defaultToolbars = [
    "filter",
    {
        icon: "layui-icon-refresh",
        title: "刷新",
        onClick: () => {
            loading.value = true;
            initDataList();
        }
    },
    "export",
]

// 获取子列
const slotChildren = computed(() =>
    // only include children that declare a customSlot to avoid generating
    // v-slot with undefined names which causes template/runtime errors
    columns.flatMap(col => (col.children || []).filter(child => child.customSlot))
)

// 下拉选择列表
const selectList = ref([])

const getSelectList = async () => {
    await api.post('resource/select', queryForm.value).then((res) => {
        if (res.code == 200) {
            console.log('@resource/select res', res)
            selectList.value = res.data
            console.log('@selectList.value', selectList.value)
        } else {
            layer.msg(res.msg, { icon: 2, time: 5000 });
        }
    })
}

const initDataList = async () => {
    loading.value = true
    await api.post("param/search", queryForm.value).then((res) => {
        console.log("@param/search:", res);
        if (res.code === 200) {
            // 将每一项的 id 转为数字
            dataSource.value = (res.data || []).map(item => ({
                ...item,
                id: Number(item.id)
            }));
            page.total = res.total;
            loading.value = false;
            getSelectList();
        } else {
            layer.msg(res.msg, { icon: 2, time: 5000 });
        }
    })
}

// 监听筛选条件变化
watch([
    () => queryForm.value.city,
    () => queryForm.value.county,
    () => queryForm.value.town,
    () => queryForm.value.forestClass,
    () => queryForm.value.ecologicalZone,
], () => {
    loading.value = true;
    initDataList();
})

onMounted(() => {
    initDataList();
    getSelectList();
})
</script>

<style scoped>
/* ::v-deep .layui-table td {
    padding: 0 !important;
    height: 35px;
    line-height: 35px;
} */
::v-deep .layui-tag-input {
    height: 22px;
}
</style>